package com.hcw.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hcw.library.common.Result;
import com.hcw.library.dao.BookTypeMapper;
import com.hcw.library.domain.Book;
import com.hcw.library.domain.BookType;
import com.hcw.library.service.BookService;
import com.hcw.library.service.BookTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookTypeServiceImpl extends ServiceImpl<BookTypeMapper, BookType> implements BookTypeService {
    @Autowired
    private BookTypeMapper bookTypeMapper;
    @Autowired
    private BookService bookService;

    @Override
    public Result<Integer> addBookType(BookType bookType) {
        Result<Integer> result = new Result<>();
        int row = bookTypeMapper.insert(bookType);
        return result.defaultSuccess(row);
    }

    @Override
    public Result<Integer> updateBookType(BookType bookType) {
        Result<Integer> result = new Result<>();
        int row = bookTypeMapper.updateById(bookType);
        return result.defaultSuccess(row);
    }

    @Override
    public Result<Integer> deleteBookType(String id) {
        Result<Integer> result = new Result<>();
        //先查询图书表中有没有该分类,将属于该分类的图书的类型置为null
        LambdaUpdateWrapper<Book> bookLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        bookLambdaUpdateWrapper.eq(Book::getTypeId,id).set(Book::getTypeId,null);
        bookService.update(bookLambdaUpdateWrapper);
        int row = bookTypeMapper.deleteById(id);
        return result.defaultSuccess(row);
    }

    @Override
    public Result<List<BookType>> queryBookTypeList() {
        Result<List<BookType>> result = new Result<>();
        List<BookType> bookTypes = bookTypeMapper.selectList(null);
        return result.defaultSuccess(bookTypes);
    }

    @Override
    public Result<BookType> queryBookTypeById(String id) {
        Result<BookType> result = new Result<>();
        BookType bookType = bookTypeMapper.selectById(id);
        return result.defaultSuccess(bookType);
    }

    @Override
    public Result<Integer> queryBookTypeByName(String typeName) {
        Result<Integer> result = new Result<>();
        QueryWrapper query = new QueryWrapper();
        query.eq("type_name", typeName);
        Integer row = bookTypeMapper.selectCount(query);
        return result.defaultSuccess(row);
    }


}
